package org.zhu.category.service.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zhu.category.mapper.CategoryMapper;
import org.zhu.category.service.CategoryService;
import org.zhu.common.bean.Category;

import java.util.List;
import java.util.Optional;

/**
 * Created by zhu yingzhi on 2017/9/6.
 * @author yingzhi zhu
 */
@Service
public class CategoryServiceImpl implements CategoryService
{
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public int insertCategory(String name,String parentPid,String categoryDesc) {
        Category category = new Category();
        category.setC_desc(categoryDesc);
        category.setName(name);
        //pid生成规则  pid在原有列表上值+1 作为唯一标识
        String categoryId = Optional.ofNullable(categoryMapper.selectParentPidAtFirst(parentPid)).
                map((s)->String.valueOf(Long.valueOf(s.getPid())+1))
                .orElseGet(()->{
                    //如果是最上级分类代表数据库还没分类 则返回100作为pid
                    if ("0".equals(parentPid)){
                        return "100";
                    }else {
                        return parentPid+"100";
                    }
                });
        category.setPid(categoryId);
        return categoryMapper.insertCategory(category);
    }

    @Override
    public List<Category> findByParentPid(String parentPid) {
        return categoryMapper.selectByParentPid(parentPid);
    }

    @Override
    public Category findOne(String pid) {
        return categoryMapper.selectOne(pid);
    }

    @Override
    public List<Category> findAll() {
        return categoryMapper.selectAll();
    }

    @Override
    public List<Category> mFindAll() {
        return categoryMapper.mSelectAll();
    }

    @Override
    public int updateName(String name,int sortOrder,String categoryDesc,String pid) {
        return categoryMapper.updateByPid(name,sortOrder,categoryDesc, pid);
    }

    @Override
    public int isShow(int isShow,String pid) {
        return categoryMapper.editIsShow(isShow,pid);
    }


}
